/*
 * PDFStreamToString.java
 * This file is part of the <a href="http://code.google.com/p/pux">PUX Framework</a>
 *
 * Copyright 2008 by <a href="mailto:jfendler@polytechnic.edu.na">Jens Fendler</a>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */
package de.teamskill.pux.library.io;

import java.io.IOException;
import java.io.InputStream;

import org.pdfbox.pdfparser.PDFParser;
import org.pdfbox.util.PDFTextStripper;

import de.teamskill.pux.engine.AbstractNode;
import de.teamskill.pux.engine.InputPort;
import de.teamskill.pux.engine.OutputPort;

/**
 * PDFStreamToString reads PDF data from an InputStream and returns the textual
 * content as a String
 * 
 * @author <a href="mailto:jfendler@polytechnic.edu.na">Jens Fendler</a>
 * 
 */
public class PDFStreamToString extends AbstractNode {

	/**
	 * IN_STREAM
	 */
	public static final String IN_STREAM = "PDFSTREAM";

	/**
	 * OUT_STRING
	 */
	public static final String OUT_STRING = "STRING";

	/**
	 * pdfStream
	 */
	private InputPort pdfStream;

	/**
	 * textString
	 */
	private OutputPort textString;

	/**
	 * PDFStreamToString Constructor
	 * 
	 */
	public PDFStreamToString() {
		this("PDFStreamToString" + nr++, false);
	}

	/**
	 * PDFStreamToString Constructor
	 * 
	 * @param nodeName
	 * @param continuous
	 */
	public PDFStreamToString(String nodeName, boolean continuous) {
		super(nodeName, continuous);
	}

	/**
	 * @see de.teamskill.pux.engine.AbstractNode#compute()
	 */
	public void compute() {
		InputStream is = (InputStream) pdfStream.fetchData();
		try {
			PDFParser p = new PDFParser(is);
			p.parse();
			PDFTextStripper s = new PDFTextStripper();
			String t = s.getText(p.getPDDocument());
			textString.pushData(t);
		} catch (IOException e) {
			throw new IllegalStateException("Error opening PDF input stream: " + e.getLocalizedMessage());
		} finally {
			try {
				is.close();
			} catch (Exception e) {
			}
		}
	}

	/**
	 * @see de.teamskill.pux.engine.AbstractNode#createPorts()
	 */
	protected void createPorts() {
		pdfStream = addInputPort(IN_STREAM, InputStream.class, true);
		textString = addOutputPort(OUT_STRING, String.class);
	}

}
